package 多线程;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class ProAndCon3 {

    public static final int MAX_SIZE = 2;
    public static BlockingDeque<Integer> queue = new LinkedBlockingDeque<>(MAX_SIZE);
    class Producer implements Runnable{

        @Override
        public void run() {
            if (queue.size()==MAX_SIZE){
                System.out.println("仓库已满，生产者"+Thread.currentThread().getName()+"不可生产");
            }
            try {
                queue.put(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("生产者"+Thread.currentThread().getName()+"生产，仓库容量为"+queue.size());
        }
    }

    class Consumer implements Runnable{

        @Override
        public void run() {
            if(queue.size()==0){
                System.out.println("仓库为空，消费者"+Thread.currentThread().getName()+"不可消费");
            }
            try {
                queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费者"+Thread.currentThread().getName()+"消费,仓库容量为"+queue.size());
        }
    }

    public static void main(String[] args) {
        ProAndCon3 proAndCon = new ProAndCon3();
        Producer producer = proAndCon.new Producer();
        Consumer consumer = proAndCon.new Consumer();
        for (int i = 0; i < 10; i++) {
            Thread pro = new Thread(producer);
            pro.start();
            Thread con = new Thread(consumer);
            con.start();
        }
    }
}
